package com.ilop.sthome.mvp.present.device;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;

import com.aliyun.iot.aep.component.router.Router;
import com.aliyun.iot.aep.sdk.apiclient.callback.IoTResponse;
import com.example.common.mvp.BasePresenterImpl;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.common.command.SendDeviceCommand;
import com.ilop.sthome.data.bean.AlarmNotice;
import com.ilop.sthome.data.enums.SmartDevice;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.data.greenDao.RoomBean;
import com.ilop.sthome.mvp.contract.device.DeviceSetContract;
import com.ilop.sthome.mvp.model.CommonModel;
import com.ilop.sthome.mvp.model.common.CommonModelImpl;
import com.example.common.mvp.onModelCallBack;
import com.ilop.sthome.ui.activity.config.AddDeviceGuideActivity;
import com.ilop.sthome.ui.activity.device.DeviceRenameActivity;
import com.ilop.sthome.ui.activity.device.DeviceShareActivity;
import com.ilop.sthome.ui.activity.device.RoomManageActivity;
import com.ilop.sthome.ui.dialog.TipDialog;
import com.ilop.sthome.ui.ota.OTAConstants;
import com.ilop.sthome.ui.ota.bean.OTADeviceInfo;
import com.ilop.sthome.ui.ota.bean.OTADeviceSimpleInfo;
import com.ilop.sthome.ui.ota.business.OTAActivityBusiness;
import com.ilop.sthome.utils.ConfigureUtil;
import com.ilop.sthome.utils.ParsingJsonUtil;
import com.ilop.sthome.utils.greenDao.utils.AutomationDaoUtil;
import com.ilop.sthome.utils.greenDao.utils.DefaultDaoUtil;
import com.ilop.sthome.utils.greenDao.utils.DeviceDaoUtil;
import com.ilop.sthome.utils.greenDao.utils.RoomDaoUtil;
import com.siterwell.familywellplus.R;

import java.util.List;

/**
 * @author skygge
 * @Date on 2020-02-13.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：
 */
public class DeviceSetPresenter extends BasePresenterImpl<DeviceSetContract.IView> implements DeviceSetContract.IPresent {

    private Context mContext;
    private int mDeviceId;
    private String mDeviceName;
    private String mNickname;
    private CommonModelImpl mModel;
    private DeviceInfoBean mDeviceInfoBean;
    private SendDeviceCommand mSendEquipment;
    private Handler mHandler;

    public DeviceSetPresenter(Context mContext, String deviceName, int deviceId) {
        this.mContext = mContext;
        this.mDeviceId = deviceId;
        this.mDeviceName = deviceName;
        mHandler = new Handler();
        mModel = new CommonModel(mHandler);
        DeviceInfoBean deviceInfoBean = DeviceDaoUtil.getInstance().findGatewayByDeviceName(deviceName);
        mSendEquipment = new SendDeviceCommand(mContext, deviceInfoBean);
    }


    @Override
    public void onRefreshView() {
        mDeviceInfoBean = DeviceDaoUtil.getInstance().findByDeviceId(mDeviceName, mDeviceId);
        if(mDeviceId==0){
            mNickname = TextUtils.isEmpty(mDeviceInfoBean.getNickName())? mContext.getString(R.string.ali_gateway):mDeviceInfoBean.getNickName();
            mView.showDeviceName(mNickname);
            if (mDeviceInfoBean.getOwned() != 1){
                mView.isSharedDevice(true);
            }
        }else {
            mNickname = TextUtils.isEmpty(mDeviceInfoBean.getSubdeviceName())? (mContext.getResources().getString(SmartDevice.getType(mDeviceInfoBean.getDevice_type()).getTypeStrId())+mDeviceInfoBean.getDevice_ID()):mDeviceInfoBean.getSubdeviceName();
            mView.showDeviceName(mNickname);
            DeviceInfoBean gateway = DeviceDaoUtil.getInstance().findGatewayByDeviceName(mDeviceName);
            if (gateway.getOwned() != 1){
                mView.isSharedDevice(false);
            }
        }
        if (mDeviceInfoBean.getRoom_id() != null){
            RoomBean room = RoomDaoUtil.getInstance().getRoomByRoomId(mDeviceInfoBean.getRoom_id());
            if (room!=null) {
                if (room.getNickname() != null) {
                    mView.showCurrentRoom(room.getNickname());
                } else {
                    mView.showCurrentRoom(ConfigureUtil.roomName(mContext, room.getRid()));
                }
            }
        }
    }

    @Override
    public void showViewByDeviceId(int deviceId) {
        if (deviceId == 0){
            getSubOffLinePush();
            mView.isGatewayView();
        }else {
            mView.isSubDeviceView();
        }
    }

    @Override
    public void setDeviceName() {
        Intent intent = new Intent(mContext, DeviceRenameActivity.class);
        intent.putExtra(CommonId.KEY_DEVICE_ID, mDeviceId);
        intent.putExtra(CommonId.KEY_DEVICE_NAME, mDeviceName);
        intent.putExtra(CommonId.KEY_NICKNAME, mNickname);
        mView.startActivityByIntent(intent);
    }

    @Override
    public void modifyRoom() {
        Intent intent = new Intent(mContext, RoomManageActivity.class);
        intent.putExtra(CommonId.KEY_BIND_ROOM, true);
        intent.putExtra(CommonId.KEY_DEVICE_ID, mDeviceId);
        intent.putExtra(CommonId.KEY_DEVICE_NAME, mDeviceName);
        mView.startActivityByIntent(intent);
    }

    @Override
    public void getDeviceNoticeList() {
        mModel.getDeviceNoticeList(mDeviceInfoBean.getIotId(), new onModelCallBack() {
            @Override
            public void onResponse(IoTResponse response) {
                List<AlarmNotice> mNoticeList = ParsingJsonUtil.getInstance().getAlarmNotice(response.getData());
                if (mNoticeList!= null && mNoticeList.size() > 0) {
                    mHandler.post(()->mView.showNoticeList(mNoticeList));
                }else {
                    mHandler.post(()->mView.withoutNotice());
                }
            }

            @Override
            public void onFailure(Exception e) {
                mHandler.post(()->mView.showToastMsg(mContext.getString(R.string.failed)));
            }
        });
    }

    @Override
    public void getSubOffLinePush() {
        mSendEquipment.queryOrSetGatewayInfo("00", "00");
    }

    @Override
    public void setSubOffLinePush(String status) {
        mSendEquipment.queryOrSetGatewayInfo("02", status);
    }

    @Override
    public void setDeviceNoticeEnabled(String eventId, boolean noticeEnabled) {
        mModel.deviceNoticeSet(mDeviceInfoBean.getIotId(), eventId, noticeEnabled, new onModelCallBack() {
            @Override
            public void onFailure(Exception e) {
                mHandler.post(()-> mView.showToastMsg(mContext.getString(R.string.operation_failed)));
            }

            @Override
            public void onResponse(IoTResponse response) {
                mHandler.post(()->{
                    if (response.getCode() ==200){
                        getDeviceNoticeList();
                        mView.showToastMsg(mContext.getString(R.string.operation_success));
                    }else {
                        mView.showToastMsg(response.getLocalizedMsg());
                    }
                });
            }
        });
    }

    @Override
    public void onUnBindDevice() {
        if(mDeviceId==0){
            String name = TextUtils.isEmpty(mDeviceInfoBean.getNickName())? mContext.getString(R.string.ali_gateway):mDeviceInfoBean.getNickName();
            TipDialog mDialog = new TipDialog(mContext, this::onUnBindGateway);
            mDialog.setMsg(String.format(mContext.getResources().getString(R.string.ali_gateay_unbind_hint), name));
            mDialog.show();
        }else {
            DeviceInfoBean deviceInfoBean1 = DeviceDaoUtil.getInstance().findGatewayByDeviceName(mDeviceInfoBean.getDeviceName());
            String name = TextUtils.isEmpty(deviceInfoBean1.getNickName())? mContext.getString(R.string.ali_gateway):deviceInfoBean1.getNickName();
            @SuppressLint({"StringFormatInvalid", "LocalSuppress"}) String title = String.format(mContext.getString(R.string.ali_delete_sub_device_from_gateway), name);
            TipDialog mDialog = new TipDialog(mContext, () -> {
                mView.showProgress();
                mSendEquipment.deleteEquipment(mDeviceId);
            });
            mDialog.setMsg(title);
            mDialog.show();
        }
    }

    @Override
    public void onUnBindGateway() {
        mView.showProgress();
        mModel.onUnbindGateway(mDeviceInfoBean.getIotId(), new onModelCallBack() {
            @Override
            public void onResponse(IoTResponse response) {
                if (response.getCode() == 200){
                    DeviceDaoUtil.getInstance().deleteAllDataWithGateway(mDeviceName);
                    mHandler.post(()-> mView.deleteSuccess());
                }else {
                    mHandler.post(()-> mView.showToastMsg(response.getLocalizedMsg()));
                }
            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }

    @Override
    public void deleteSuccess() {
        DeviceDaoUtil.getInstance().deleteByDeviceName(mDeviceName, mDeviceId);
        DefaultDaoUtil.getInstance().deleteByDeviceId(mDeviceName, mDeviceId);
        AutomationDaoUtil.getInstance().deleteBySubDevice(mDeviceName, mDeviceId);
        mHandler.post(()-> mView.deleteSuccess());
    }

    @Override
    public void skipToShared() {
        Intent intent = new Intent(mContext, DeviceShareActivity.class);
        intent.putExtra(CommonId.KEY_IOT_ID, mDeviceInfoBean.getIotId());
        mView.startActivityByIntent(intent);
    }

    @Override
    public void onReplaceDevice() {
        if(mDeviceId>0){
            Intent intent = new Intent(mContext, AddDeviceGuideActivity.class);
            intent.putExtra(CommonId.KEY_DEVICE_TYPE, mDeviceInfoBean.getDevice_type());
            intent.putExtra(CommonId.KEY_DEVICE_NAME, mDeviceName);
            intent.putExtra(CommonId.KEY_DEVICE_ID, mDeviceId);
            mView.startActivityByIntent(intent);
        }
    }

    @Override
    public void requestNewVersion() {
        Handler handler = new Handler(msg -> {
            if (OTAConstants.MINE_MESSAGE_RESPONSE_OTA_DEVICE_INFO_SUCCESS == msg.what) {
                OTADeviceInfo info = (OTADeviceInfo) msg.obj;
                if (null != info) {
                    if (null != info.otaFirmwareDTO) {
                        mView.showNewVersion(true);
                    }
                    if (null != info.otaUpgradeDTO) {
                        int status = Integer.parseInt(info.otaUpgradeDTO.upgradeStatus);
                        if (OTAConstants.OTA_STATUS_DONE == status) {
                            mView.showNewVersion(false);
                        }
                    }
                }
            }
            return false;
        });
        OTAActivityBusiness mBusiness = new OTAActivityBusiness(handler);
        mBusiness.generateOTAManager(handler, mDeviceInfoBean.getIotId(), "NET_WIFI");
        mBusiness.requestDeviceInfo();
    }

    @Override
    public void onRouterToOTA() {
        if(mDeviceId==0){
            OTADeviceSimpleInfo info = new OTADeviceSimpleInfo();
            info.iotId = mDeviceInfoBean.getIotId();
            info.deviceName = mDeviceName;
            Bundle bundle = new Bundle();
            bundle.putParcelable(OTAConstants.OTA_KEY_DEVICESIMPLE_INFO, info);
            Router.getInstance().toUrl(mContext, OTAConstants.MINE_URL_OTA, bundle);
        }
    }
}
